package com.itheima;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.TimeUnit;

/**
 * @program: curator-zk
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-07 20:33
 **/
public class Ticket12306 implements Runnable {
    private volatile int ticket = 10;
    InterProcessMutex lock;
    
    public Ticket12306() {
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(
                3000, 3);
        
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("192.168.23.129:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(10 * 1000)
                .retryPolicy(retryPolicy)
                //命名空间,都是在这个节点下
                .namespace("itheima1")
                .build();
        //开启连接
        client.start();
        lock = new InterProcessMutex(client, "/create1");
    }
    
    @Override
    public void run() {
        while (true) {
            try {
                lock.acquire(3000, TimeUnit.MILLISECONDS);
                if (ticket > 0) {
                    System.out.println(Thread.currentThread().getName() + " : " + ticket);
                    // Thread.sleep(1000);
                    ticket--;
                } else {
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
